package cn.initcap.bio.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @author initcap
 * @date Created in 4/25/19 4:35 PM.
 */
public class UdpClient {

    public static void main(String[] args) throws IOException {
        //1. 定义服务器的地址、端口号、数据
        InetAddress address = InetAddress.getByName("localhost");
        int port = 8889;
        byte[] data = "用户名:admin,密码:123".getBytes();
        //2. 创建数据报，包含发送的信息
        DatagramPacket datagramPacket = new DatagramPacket(data, data.length, address, port);
        //3. 创建DatagramSocket对象
        DatagramSocket datagramSocket = new DatagramSocket();
        //4. 向服务器发送数据报
        datagramSocket.send(datagramPacket);

        /**
         * 接受服务器端响应数据
         */
        //1. 创建数据报，用于接收服务器端的响应数据
        byte[] dataResult = new byte[1024];
        DatagramPacket packet = new DatagramPacket(dataResult, dataResult.length);
        //2. 接收服务器的响应数据
        datagramSocket.receive(packet);
        //3. 读取服务器端响应的数据
        String reply = new String(dataResult, 0, dataResult.length);
        System.out.println("我是客户端，服务器说: " + reply);
        //4. 关闭资源
        datagramSocket.close();
    }

}
